package com.example.ssd4.view;

import com.example.ssd4.domain.Lesson;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NewLessonDialog extends Application {
    private static int num;
    private TeacherDialog teacherDialog;
    private String account;
    private VBox mainVBox;
    private Stage thisStage;
    private Label id;
    private TextField name;
    private GridPane insidePane;
    private Spinner<Integer> weekStart;
    private Spinner<Integer> weekEnd;
    private Spinner<Integer> number;
    private ComboBox[] days;
    private ComboBox[] times;
    private String timeString;
    private Lesson lesson;
    private TextField teacher;
    private Spinner<Integer> credit;
    private ComboBox<String> attribute;
    private Spinner<Integer> capacity;
    private Button foundLesson;
    private Button returnBtn;
    private SpinnerValueFactory<Integer> weekStartValue;
    private SpinnerValueFactory<Integer> weekEndValue;
    private SpinnerValueFactory<Integer> numberValue;
    private SpinnerValueFactory<Integer> creditValue;
    private SpinnerValueFactory<Integer> capacityValue;
    private Scene scene;

    //课程id
    Label idLbl;
    //课程名称
    Label nameLbl;
    //授课教师
    Label teacherLbl;
    //上课周数
    Label weekLbl;
    //至
    Label weekToLbl;
    //周
    Label weekEndLbl;
    //每周节次
    Label numberLbl;
    //课程学分
    Label creditLbl;
    //课程性质
    Label attributeLbl;
    //最大学生
    Label capacityLbl;


    public void start(Stage stage) throws Exception {
        mainVBox = new VBox();
        scene = new Scene(mainVBox,500,555);
        LoginDialog.addGlobalShortcut(scene);
        thisStage = stage;

        initGraphic();
        initAction();
        setId();
        thisStage.setOnCloseRequest(windowEvent -> {
            name.setText("1");
            teacher.setText("1");
        });
        thisStage.setScene(scene);
        thisStage.show();
    }

    private void initGraphic() {
        HBox hBox = new HBox();
        Text text = new Text("  新建课程");
        text.setFont(Font.font("微软雅黑", FontWeight.BOLD,25));
        Image image = new Image("file:src/main/resources/image/logo3_proc.jpg");
        ImageView imageView = new ImageView(image);
        hBox.getChildren().addAll(imageView,text);
        mainVBox.getChildren().add(hBox);
        GridPane gridPane = new GridPane();
        mainVBox.getChildren().add(gridPane);

        idLbl = new Label("课程ID:");
        idLbl.setStyle("-fx-font-size: 15px;");
        nameLbl = new Label("课程名称:");
        nameLbl.setStyle("-fx-font-size: 15px;");
        teacherLbl = new Label("授课教师:");
        teacherLbl.setStyle("-fx-font-size: 15px;");
        id = new Label();
        id.setStyle("-fx-font-size: 15px;" +
                "-fx-font-weight: bold;");
        name = new TextField();
        teacher = new TextField();

        gridPane.add(idLbl,0,0);
        gridPane.add(id,1,0);
        gridPane.add(nameLbl,0,1);
        gridPane.add(name,1,1);
        gridPane.add(teacherLbl,0,2);
        gridPane.add(teacher,1,2);

        weekLbl = new Label("上课周数:");
        weekLbl.setStyle("-fx-font-size: 15px;");
        HBox weekHBox = new HBox();
        weekToLbl = new Label("   至   ");
        weekToLbl.setStyle("-fx-font-size: 15px;");
        weekEndLbl = new Label("    周");
        weekEndLbl.setStyle("-fx-font-size: 15px;");
        weekStart = new Spinner<>(0,19,1);
        weekStart.setPrefWidth(150);
        weekEnd = new Spinner<>(0,19,18);
        weekEnd.setPrefWidth(150);
        weekHBox.getChildren().addAll(weekStart,weekToLbl,weekEnd,weekEndLbl);
        weekHBox.setAlignment(Pos.CENTER);

        gridPane.add(weekLbl,0,3);
        gridPane.add(weekHBox,1,3);

        numberLbl = new Label("每周节次:");
        numberLbl.setStyle("-fx-font-size: 15px;");
        number = new Spinner<>(0,5,2);
        number.setPrefWidth(150);
        insidePane = new GridPane();
        GridPane.setColumnSpan(insidePane,2);

        //选择课程时间
        days=new ComboBox[4];
        times=new ComboBox[4];
        for(int i=0;i<4;i++){
            days[i]=new ComboBox<>();
            days[i].getItems().addAll("星期1","星期2","星期3","星期4","星期5");
            days[i].setValue("星期"+(i+1));
            days[i].setMinWidth(150);
            times[i]=new ComboBox<>();
            times[i].getItems().addAll("01-02节","03-04节","05-06节","07-08节","09-10节");
            times[i].setValue("0"+(2*i+1)+"-0"+2*(i+1)+"节");
            times[i].setMinWidth(200);

        }
        setInsidePane(2);

        gridPane.add(numberLbl,0,4);
        gridPane.add(number,1,4);
        gridPane.add(insidePane,0,5);

        creditLbl = new Label("课程学分:");
        creditLbl.setStyle("-fx-font-size: 15px;");
        attributeLbl = new Label("课程性质:");
        attributeLbl.setStyle("-fx-font-size: 15px;");
        capacityLbl = new Label("最大学生:");
        capacityLbl.setStyle("-fx-font-size: 15px;");
        credit = new Spinner<>(0,6,2);
        attribute = new ComboBox<>();
        attribute.getItems().addAll("选修","公选");
        attribute.setValue("公选");
        capacity = new Spinner<>(29,91,60);

        gridPane.add(creditLbl,0,6);
        gridPane.add(credit,1,6);
        gridPane.add(attributeLbl,0,7);
        gridPane.add(attribute,1,7);
        gridPane.add(capacityLbl,0,8);
        gridPane.add(capacity,1,8);

        returnBtn = new Button("返回");
        returnBtn.setStyle(
                "-fx-pref-width: 240px;-fx-pref-height: 30px;"+
                        "-fx-background-color: #FF0060;"+
                        "-fx-border-radius: 60px;"+
                        "-fx-font-size: 15px;"+
                        "-fx-text-fill: WHITE;"+
                        "-fx-font-weight: bold;");
        foundLesson=new Button("创建");
        foundLesson.setStyle(
                "-fx-pref-width: 240px;-fx-pref-height: 30px;"+
                        "-fx-background-color: #215496;"+
                        "-fx-border-radius: 60px;"+
                        "-fx-font-size: 15px;"+
                        "-fx-text-fill: WHITE;"+
                        "-fx-font-weight: bold;");
        HBox buttonHBox = new HBox();
        buttonHBox.getChildren().addAll(returnBtn,foundLesson);
        buttonHBox.setSpacing(20);
        mainVBox.getChildren().add(buttonHBox);

        //整体布局调整
        mainVBox.setPadding(new Insets(20));
        mainVBox.setSpacing(20);
        gridPane.setVgap(15);
        gridPane.setHgap(10);
        insidePane.setHgap(20);
        insidePane.setVgap(15);
        mainVBox.setAlignment(Pos.CENTER);
    }

    private void initAction() {

        //课程名称
        //Label nameLbl;
        nameLbl.setOnMouseClicked(event -> {
            name.requestFocus();
            name.selectAll();  // 全选TextField中的文本
        });
        //授课教师
        //Label teacherLbl;
        teacherLbl.setOnMouseClicked(event -> {
            teacher.requestFocus();
            teacher.selectAll();  // 全选TextField中的文本
        });
        //上课周数
        //Label weekLbl;
        weekLbl.setOnMouseClicked(event -> {
            weekStart.requestFocus();
        });
        //至
        //Label weekToLbl;
        weekToLbl.setOnMouseClicked(event -> {
            weekEnd.requestFocus();
        });
        //每周节次
        //Label numberLbl;
        numberLbl.setOnMouseClicked(event -> {
            number.requestFocus();
        });
        //课程学分
        //Label creditLbl;
        creditLbl.setOnMouseClicked(event -> {
            credit.requestFocus();
        });
        //最大学生
        //Label capacityLbl;
        capacityLbl.setOnMouseClicked(event -> {
            capacity.requestFocus();
        });

        //几个spinner的初始化
        weekStart.setEditable(true);
        weekEnd.setEditable(true);
        number.setEditable(true);
        credit.setEditable(true);
        capacity.setEditable(true);

        weekStartValue = new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 19, 1);
        weekEndValue = new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 19, 18);
        numberValue = new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 5, 1);
        creditValue = new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 19, 18);
        capacityValue = new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 5, 1);

        weekStart.valueProperty().addListener(new ChangeListener<Integer>() {
            @Override
            public void changed(ObservableValue<? extends Integer> observable, Integer oldValue, Integer newValue) {
                if(newValue<=0){
                   weekStartValue.setValue(1);
                   weekStart.setValueFactory(weekStartValue);
                }
                else if(newValue>=weekEnd.getValue()){
                    weekStartValue.setValue(weekEnd.getValue()-1);
                    weekStart.setValueFactory(weekStartValue);
                }
            }
        });
        weekEnd.valueProperty().addListener(new ChangeListener<Integer>() {
            @Override
            public void changed(ObservableValue<? extends Integer> observable, Integer oldValue, Integer newValue) {
                if(newValue<=weekStart.getValue()){
                    weekEndValue.setValue(weekStart.getValue()+1);
                    weekEnd.setValueFactory(weekEndValue);
                }
                else if(newValue>=19){
                    weekEndValue.setValue(18);
                    weekEnd.setValueFactory(weekEndValue);
                }
            }
        });
        number.valueProperty().addListener(new ChangeListener<Integer>() {
            @Override
            public void changed(ObservableValue<? extends Integer> observable, Integer oldValue, Integer newValue) {
                if(newValue<=0){
                    numberValue.setValue(4);
                    number.setValueFactory(numberValue);
                }
                else if(newValue>=5){
                    numberValue.setValue(1);
                    number.setValueFactory(numberValue);
                }
                setInsidePane(number.getValue());
            }
        });
        credit.valueProperty().addListener(new ChangeListener<Integer>() {
            @Override
            public void changed(ObservableValue<? extends Integer> observable, Integer oldValue, Integer newValue) {
                if(newValue<=0){
                    creditValue.setValue(5);
                    credit.setValueFactory(creditValue);
                }
                else if(newValue>=6){
                    creditValue.setValue(1);
                    credit.setValueFactory(creditValue);
                }
            }
        });
        capacity.valueProperty().addListener(new ChangeListener<Integer>() {
            @Override
            public void changed(ObservableValue<? extends Integer> observable, Integer oldValue, Integer newValue) {
                if(newValue<=29){
                    capacityValue.setValue(90);
                    capacity.setValueFactory(capacityValue);
                }
                else if(newValue>=91){
                    capacityValue.setValue(30);
                    capacity.setValueFactory(capacityValue);
                }
            }
        });


        //对days和times的监听
            days[0].valueProperty().addListener(new ChangeListener<String>() {
                @Override
                public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                    for (int n = 0; n < 4; n++) {
                        if (n!=0) {
                            if (newValue == days[n].getValue()&&times[0].getValue()==times[n].getValue()) {
                                 days[0].setValue(oldValue);
                                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                                alert.setTitle("");
                                alert.setHeaderText("Sorry");
                                alert.setContentText("不同选择相同时间");
                                alert.showAndWait();
                            }
                        }
                    }
                }
            });
        days[1].valueProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                for (int n = 0; n < 4; n++) {
                    if (n!=1) {
                        if (newValue == days[n].getValue()&&times[1].getValue()==times[n].getValue()) {
                            days[1].setValue(oldValue);
                            Alert alert = new Alert(Alert.AlertType.INFORMATION);
                            alert.setTitle("");
                            alert.setHeaderText("Sorry");
                            alert.setContentText("不同选择相同时间");
                            alert.showAndWait();
                        }
                    }
                }
            }
        });
        days[2].valueProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                for (int n = 0; n < 4; n++) {
                    if (n!=2) {
                        if (newValue == days[n].getValue()&&times[2].getValue()==times[n].getValue()) {
                            days[2].setValue(oldValue);
                            Alert alert = new Alert(Alert.AlertType.INFORMATION);
                            alert.setTitle("");
                            alert.setHeaderText("Sorry");
                            alert.setContentText("不同选择相同时间");
                            alert.showAndWait();
                        }
                    }
                }
            }
        });
        days[3].valueProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                for (int n = 0; n < 4; n++) {
                    if (n!=3) {
                        if (newValue == days[n].getValue()&&times[3].getValue()==times[n].getValue()) {
                            days[3].setValue(oldValue);
                            Alert alert = new Alert(Alert.AlertType.INFORMATION);
                            alert.setTitle("");
                            alert.setHeaderText("Sorry");
                            alert.setContentText("不同选择相同时间");
                            alert.showAndWait();
                        }
                    }
                }
            }
        });
        times[0].valueProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                for (int n = 0; n < 4; n++) {
                    if (n!=0) {
                        if (newValue == times[n].getValue()&&days[0].getValue()==days[n].getValue()) {
                            times[0].setValue(oldValue);
                            Alert alert = new Alert(Alert.AlertType.INFORMATION);
                            alert.setTitle("");
                            alert.setHeaderText("Sorry");
                            alert.setContentText("不同选择相同时间");
                            alert.showAndWait();
                        }
                    }
                }
            }
        });
        times[1].valueProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                for (int n = 0; n < 4; n++) {
                    if (n!=1) {
                        if (newValue == times[n].getValue()&&days[1].getValue()==days[n].getValue()) {
                            times[1].setValue(oldValue);
                            Alert alert = new Alert(Alert.AlertType.INFORMATION);
                            alert.setTitle("");
                            alert.setHeaderText("Sorry");
                            alert.setContentText("不同选择相同时间");
                            alert.showAndWait();
                        }
                    }
                }
            }
        });
        times[2].valueProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                for (int n = 0; n < 4; n++) {
                    if (n!=2) {
                        if (newValue == times[n].getValue()&&days[2].getValue()==days[n].getValue()) {
                            times[2].setValue(oldValue);
                            Alert alert = new Alert(Alert.AlertType.INFORMATION);
                            alert.setTitle("");
                            alert.setHeaderText("Sorry");
                            alert.setContentText("不同选择相同时间");
                            alert.showAndWait();
                        }
                    }
                }
            }
        });
        times[3].valueProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                for (int n = 0; n < 4; n++) {
                    if (n!=3) {
                        if (newValue == times[n].getValue()&&days[3].getValue()==days[n].getValue()) {
                            times[3].setValue(oldValue);
                            Alert alert = new Alert(Alert.AlertType.INFORMATION);
                            alert.setTitle("");
                            alert.setHeaderText("Sorry");
                            alert.setContentText("不同选择相同时间");
                            alert.showAndWait();
                        }
                    }
                }
            }
        });
        //对课程名和老师名的判定
        name.focusedProperty().addListener((observable, oldValue, newValue) -> {
            if (!newValue) {
                if(name.getText().trim().length()==0){
                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                    alert.setTitle("");
                    alert.setHeaderText("Sorry");
                    alert.setContentText("课程名不能为空");
                    alert.showAndWait();
                    //name.requestFocus();
                }
            }
        });

        teacher.focusedProperty().addListener((observable, oldValue, newValue) -> {
            /*if(name.getText().trim().equals("")) {
                name.requestFocus();
                return;
            }
            */
            if (!newValue) {
                if(teacher.getText().trim().length()==0){
                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                    alert.setTitle("");
                    alert.setHeaderText("Sorry");
                    alert.setContentText("姓名不能为空");
                    alert.showAndWait();
                    //teacher.requestFocus();
                }
            }
        });
        //创建课程事件
        foundLesson.setOnAction(actionEvent -> {
            if(teacher.getText().trim().length()==0||name.getText().trim().length()==0){
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("");
                alert.setHeaderText("Sorry");
                alert.setContentText("信息填补不全");
                alert.showAndWait();
                return;
            }
            timeString="";
            timeString+=weekStart.getValue();
            timeString+="~";
            timeString+=weekEnd.getValue();
            timeString+=" ";
            for(int i=0;i<num;i++){
                timeString+=days[i].getValue().toString().charAt(2);
                timeString+="-";
                timeString+=times[i].getValue().toString().substring(0,2)+times[i].getValue().toString().substring(3,5);
                if(i!=num-1){
                    timeString+=",";
                }
            }
            lesson=new Lesson(id.getText(),name.getText().trim(),timeString,teacher.getText().trim(),"无记录",credit.getValue().toString(),attribute.getValue(),capacity.getValue().toString());

            Lesson.addLessonToFile(lesson,"src\\main\\resources\\data\\lesson.log");
            Lesson.addLessonToFile(lesson,"src\\main\\resources\\data\\teacher\\"+ account + ".log");

            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("新建课程");
            alert.setHeaderText("新建课程");
            alert.setContentText("课程（" + lesson.getName() + "）创建成功");
            alert.show();

            teacherDialog.updateAddLesson();

            thisStage.close();
        });

        thisStage.setOnCloseRequest(windowEvent -> {
            returnBtn.fire();
            windowEvent.consume();
        });

        returnBtn.setOnAction(actionEvent -> {
            Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
            alert.setTitle("返回");
            alert.setHeaderText("确认操作");
            alert.setContentText("你确定要返回吗？");

            // 创建自定义按钮
            ButtonType confirmButtonType = new ButtonType("确定", ButtonBar.ButtonData.YES);
            ButtonType cancelButtonType = new ButtonType("取消", ButtonBar.ButtonData.NO);

            // 设置按钮
            alert.getButtonTypes().setAll(cancelButtonType, confirmButtonType);

            Platform.runLater(() -> {
                Button confirmButton = (Button) alert.getDialogPane().lookupButton(cancelButtonType);
                confirmButton.setStyle("-fx-background-color: #f87f7f;"); // 设置红色背景
                alert.getDialogPane().lookupButton(cancelButtonType).requestFocus(); // 设置焦点到"取消"按钮
            });

            // 显示并等待响应
            alert.showAndWait().ifPresent(response -> {
                if (response == confirmButtonType) {
                    thisStage.close();
                }
            });
        });
    }
    private void setInsidePane(int i){
        num=i;
        insidePane.getChildren().clear();
        for(int n=0;n<i;n++) {
            insidePane.add(days[n], 0, n);
            insidePane.add(times[n], 1, n);
        }
    }
    private void setId(){
        String data ="";
        try (BufferedReader reader = new BufferedReader(new FileReader("src\\main\\resources\\data\\lesson.log"))) {
            // 读取文件内容
            String line;
            while ((line = reader.readLine()) != null) {
                String regex = "\"([^\"]*)\"";
                Pattern pattern = Pattern.compile(regex);
                Matcher matcher = pattern.matcher(line);
                  if(matcher.find()) {
                    data=matcher.group(1);
                }
            }
            data=data.substring(0,data.length()-2)+(Integer.parseInt(data.substring(data.length()-2,data.length()))+1);
        }catch (IOException e) {
            e.printStackTrace();
        }
           id.setText(data);
    }

    public void initAccount(String account,TeacherDialog teacherDialog){
        this.account = account;
        this.teacherDialog = teacherDialog;
    }
}
